package elmar.swt;

import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.*;

public class Treemaker {

	public static void main(String[] args) {
		final Display display = new Display();
		final Shell shell = new Shell(display);
		final int treeData[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15 };
		final int CIRCLE_SIZE = 20;
		final int nHalfUnit = BinTreeCoordinateHelper
				.getNHalfUnitX(treeData.length);
		shell.addPaintListener(new PaintListener() {
			public void paintControl(PaintEvent event) {
				Rectangle rect = shell.getClientArea();
				int height = BinTreeCoordinateHelper
						.getPosY(treeData.length - 1) + 1;
				int halfUnitLenghtX = (rect.width - CIRCLE_SIZE) / nHalfUnit;
				int halfUnitLenghtY = (rect.height - CIRCLE_SIZE)
						/ (height - 1);
				for (int i = 0; i < treeData.length; i++) {
					int x = BinTreeCoordinateHelper.getPosX(i);
					int y = BinTreeCoordinateHelper.getPosY(i);
					
					int offsetX = 0;
					if(y==height-2)offsetX = halfUnitLenghtX+CIRCLE_SIZE;
					if(y<height-2)offsetX = (height-1-y)*halfUnitLenghtX+CIRCLE_SIZE/2;
					if(y!=height-1){
						offsetX -= CIRCLE_SIZE/2;
					}
					int offsetY = (y) * halfUnitLenghtY;
					event.gc.drawOval(offsetX, offsetY, CIRCLE_SIZE, CIRCLE_SIZE);
					if(i!=0){
						int moreX = i%2==1?halfUnitLenghtX:-halfUnitLenghtX;
						event.gc.drawLine(offsetX+CIRCLE_SIZE/2, offsetY+CIRCLE_SIZE/2, offsetX+moreX/2+CIRCLE_SIZE/2, offsetY-halfUnitLenghtY+CIRCLE_SIZE/2);
					}
				}
//				event.gc.drawOval(0, 0, rect.width - 1, rect.height - 1);
			}
		});
//		shell.setBounds(10, 10, 200, 200);
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}
}